package com.ruoyi.yl.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.yl.domain.Users;
import com.ruoyi.yl.mapper.UsersMapper;
import com.ruoyi.yl.service.IUsersService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author jiabao
 * @since 2025-06-25
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Override
    public Users selectByOpenId(String openId) {
        return this.getBaseMapper().selectOne(Wrappers.<Users>lambdaQuery()
                .eq(openId != null, Users::getOpenid, openId)
        );
    }

    @Override
    public Users selectById(Long userId) {

        return this.getBaseMapper().selectOne(Wrappers.<Users>lambdaQuery()
                .eq( Users::getId, userId)
        );
    }

    @Override
    public Users initUser(Users user) {
        this.getBaseMapper().insert(user);
        return this.selectByOpenId(user.getOpenid());
    }

    @Override
    public void updateLoginTime(Long userId) {
        if (userId==null){return;}

        this.getBaseMapper().update(Wrappers.<Users>lambdaUpdate()
                .eq(Users::getId, userId)
                .set(Users::getUpdatedAt, LocalDateTime.now())
        );
    }

    @Override
    public void decodePoint(BigDecimal demandAmount) {
        Users users = this.getById(SecurityUtils.getUserId());
        users.setPoints(users.getPoints()-demandAmount.intValue());
        this.updateById(users);
    }
}
